/**
 * 基于IndexDB封装的仿localStage用法的工具
 * **/

import { appConfig, settingConfig } from "@/config";

function promisify(request) {
    return new Promise((resolve, reject) => {
        request.onsuccess = () => resolve(request.result);
        request.onerror = () => reject(request.error);
    });
}
class DBStorage {
    constructor(dbName, storeName) {
        const request = window.indexedDB.open(dbName);
        request.onupgradeneeded = () =>
            request.result.createObjectStore(storeName);
        this.dbPromise = promisify(request);
        this.storeName = storeName;
    }
    async getStore(operationMode, storeName = this.storeName) {
        const db = await this.dbPromise;
        return db.transaction(storeName, operationMode).objectStore(storeName);
    }
    async setItem(key, value) {
        const store = await this.getStore("readwrite");
        return promisify(store.put(value, key));
    }
    async getItem(key) {
        const store = await this.getStore("readonly");
        return promisify(store.get(key));
    }
    async removeItem(key) {
        const store = await this.getStore("readwrite");
        return promisify(store.delete(key));
    }
    async clear() {
        const store = await this.getStore("readwrite");
        return promisify(store.clear());
    }
}

/**
 * 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 * @method 废弃
 */
class MyNewLocalStorage {
    setStorage(key = "", value = {}) {
        try {
            window.localStorage.setItem(
                `${settingConfig.storagePrefix}${key}`,
                JSON.stringify(value)
            );
        } catch (error) {
            console.error(error);
        }
    }
    getStorage(key = "") {
        try {
            const value = window.localStorage.getItem(
                `${settingConfig.storagePrefix}${key}`
            );
            return JSON.parse(value || {});
        } catch (error) {
            console.error(error);
        }
    }
    removeStorage(key = "") {
        try {
            window.localStorage.removeItem(key);
        } catch (error) {
            console.error(error);
        }
    }

    clearStorage() {
        try {
            window.localStorage.clear();
        } catch (err) {
            console.error(err);
        }
    }
}

/**
 * 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 */

import {
    getKeys,
    setKeys,
    removeKeys,
    mapToObj,
    objTransformMap,
} from "./useKeys";

class MyLocalStorage {
    storage;
    config;
    constructor(config) {
        this.config = config;
        this.storage = window[config.type];
    }

    set(key = "", value) {
        try {
            this.storage.setItem(setKeys(key), JSON.stringify(value));
        } catch (error) {
            console.error(error);
        }
    }

    get(key) {
        try {
            const value = this.storage.getItem(getKeys(key));
            if (typeof value === 'object') return JSON.parse(value)
            else return JSON.parse(value || '')
        } catch (error) {
            console.error(error);
        }
    }

    remove(key) {
        try {
            this.storage.removeItem(removeKeys(key));
        } catch (error) {
            console.error(error);
        }
    }

    clear() {
        try {
            this.storage.clear();
        } catch (error) {
            console.error(error);
        }
    }

    setMap(key, map) {
        try {
            const mapObj = mapToObj(map);
            this.storage.setItem(setKeys(key), JSON.stringify(mapObj));
        } catch (err) {
            console.error(err);
        }
    }

    getMap(key) {
        try {
            const value = this.storage.getItem(getKeys(key));
            if (value) return objTransformMap(JSON.parse(value));
        } catch (err) {
            console.error(err);
        }
    }
}

const dbStorage = new DBStorage(
    settingConfig.indexedDBDataSource,
    settingConfig.indexedDBDataTable
);
const myLocalStorage = new MyLocalStorage({type: appConfig.storageType});

export { dbStorage, myLocalStorage as db };
